knitr::opts_chunk$set(echo = FALSE)
library(dplyr)
library(kableExtra)

# Load data
load("vt.RData")
load("data/sfgs_2020.RData")

# Get data for analysis
vt_pty <- full_join(vt, sfgs %>%
                      select(responded, pid_3, id) %>%
                      mutate(id = as.numeric(id)),
                    by = "id") %>%
  rename(pty = PARTY_AFFILIATION) %>%
  mutate(pty_col = if_else(pty == "IND" | pty == "NPA", "IND-NPA", pty)) %>%
  filter(pty == "REP" | pty == "DEM" | pty == "IND" | pty == "NPA")

n_sfgs <- nrow(sfgs)

rm(sfgs)


table(vt_pty$pty)


pty_prop <- tibble(Party = c("Democrat",
                             "Ind.-No Party Affiliation",
                             "Republican"),
                   `Population (%)` = as.numeric(proportions(table(vt_pty$pty_col))) * 100,
                   `Sample (%)` = as.numeric(proportions(table(vt_pty$pty_col[vt_pty$responded == 1]))) * 100) %>%
  mutate(`Difference (p.p.)` = `Population (%)` - `Sample (%)`)



nr <- as.table(cbind(table(vt_pty$pty_col),
                     table(vt_pty$pty_col[vt_pty$responded == 1])))

dimnames(nr) <- list(party = c("DEM","IND-NPA", "REP"),
                     group = c("Pop", "Sample"))

chisq.test(nr)

# Prop tests - Dems
prop.test(x = nr[1,],
          n = colSums(nr))

# Prop tests - Ind-NPA
prop.test(x = nr[2,],
          n = colSums(nr))

# Prop tests - Rep
prop.test(x = nr[3,],
          n = colSums(nr))



kbl(pty_prop, digits = 2, format = "pipe",
    align = 'lccc',
    caption = "Evaluation of Partisan Unit Non-Response Bias",
    cetering = T)

